'use strict';
const {
  Model
} = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class Course extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // 定义与 User 的关联
      Course.belongsTo(models.User, {
        foreignKey: 'userId',
        as: 'user'
      });
      
      // 定义与 Category 的关联
      Course.belongsTo(models.Category, {
        foreignKey: 'categoryId',
        as: 'category'
      });
    }
  }
  Course.init({
    categoryId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: {
          msg: '分类id不能为空'
        },
        isInt: {
          msg: '分类id必须是整数'
        },
        notEmpty: {
          msg: '分类id不能为空'
        },
        async isExist(value) {
          const category = await sequelize.models.Category.findByPk(value);
          if (!category) {
            throw new Error('所选分类不存在');
          }
        }
      }
    },
    userId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      validate: {
        notNull: {
          msg: '用户id不能为空'
        },
        isInt: {
          msg: '用户id必须是整数'
        },
        async isExist(value) {
          const user = await sequelize.models.User.findByPk(value);
          if (!user) {
            throw new Error('用户不存在');
          }
        }
      }
    },
    name: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {
          msg: '课程名称不能为空'
        },
        len: {
          args: [2, 50],
          msg: '课程名称长度必须在2-50个字符之间'
        }
      }
    },
    image: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        notNull: {
          msg: '课程图片不能为空'
        },
        isUrl: {
          msg: '图片必须是有效的URL地址'
        }
      }
    },
    recommended: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    introductory: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false
    },
    content: {
      type: DataTypes.TEXT,
      allowNull: false,
      validate: {
        notNull: {
          msg: '课程内容不能为空'
        },
        notEmpty: {
          msg: '课程内容不能为空'
        }
      }
    },
    likeCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      validate: {
        isInt: {
          msg: '点赞数必须是整数'
        },
        min: {
          args: [0],
          msg: '点赞数不能小于0'
        }
      }
    },
    chaptersCount: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      validate: {
        isInt: {
          msg: '章节数必须是整数'
        },
        min: {
          args: [0],
          msg: '章节数不能小于0'
        }
      }
    }
  }, {
    sequelize,
    modelName: 'Course',
  });
  return Course;
};